﻿
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using c_FormMover;
using n_GFilePanel;
using n_GUIset;
using n_LaterFilesManager;
using n_OS;
using s_Win32;
using n_ClearChipForm;
using n_UserModule;
using n_SimulateObj;
using n_myTabControl;
using n_FileTabPage;
using n_LaterFilePanel;
using n_ctext;
using n_NewVersionForm;
using n_PyPanel;
using n_PyVM;
using n_ErrorListBox;
using n_OutputBox;
using n_CodePanel;
using n_FileType;

namespace v_GForm
{
public partial class GForm : Form
{
	FormMover fm;
	GFilePanel myGFilePanel;
	CodePanel CPanel;
	
	const int MovePadding = 5;
	const int TopPadding = 5;
	const int LeftPadding = 5;
	const int RightPadding = 5;
	const int BottomPadding = 5;
	
	const int WM_HOTKEY = 0x312; //窗口消息：热键
    const int WM_CREATE = 0x1; //窗口消息：创建
    const int WM_DESTROY = 0x2; //窗口消息：销毁
    const int HotKeyID = 1; //热键ID（自定义）
	
	string AFileName;
	
	const int MaxLength = 500;
	static byte[] PortBuffer;
	int CIndex;
	int RIndex;
	
	//CTextBox UserText;
	//CTextBox SysText;
	
	//RichTextBox UserText;
	
	bool isNew = true;
	bool BindExt;
	
	int SplitValue = 0;
	
	//主窗口
	public GForm( string StartFileName )
	{
		InitializeComponent();
		
		A.StartBox.AddMessage( "\n" );
		/*
		TexttabControl = new myTabControl();
		TexttabControl.Dock = DockStyle.Fill;
		//TexttabControl.SendToBack();
		//this.splitContainerMain.Panel2.Controls.Add( TexttabControl );
		this.splitContainer3.Panel1.Controls.Add( TexttabControl );
		FileTabPage filePanel = new FileTabPage( StartFileName, TexttabControl, null );
		
		//需要加上这一项
		filePanel.SetCurrent();
		*/
		
		n_ControlCenter.ControlCenter.D_StartCompile = Start;
		n_ControlCenter.n_CThread.CThread.D_ShowError = ShowError;
		n_ControlCenter.n_CThread.CThread.D_HiddError = HiddError;
		
		n_SwitchTip.SwitchTip.deleOpenFile = OpenFile;
		
		//n_GUIcoder.GUIcoder.mySetLoadProgress = SetLoadProgress;
		
		T.T.G_Init();
		CPanel = new CodePanel();
		CPanel.Sys_ctext.EnableColor = false;
		this.splitContainer3.Panel1.Controls.Add( CPanel );
		
		A.StartBox.AddMessage( "\n" );
		
		OutputBox.Init( this.tabControl1 );
		//this.tabControl1.Controls.Add( OutputBox.Init( this.tabControl1 ) );
		this.tabControl1.Controls.Add( ErrorListBox.Init( this.tabControl1 ) );
		
		splitContainer3.SplitterDistance = splitContainer3.Height;
		
		if( !isNew ) {
			this.Padding = new Padding( LeftPadding, TopPadding, RightPadding, BottomPadding );
		}
		
		//防止最大化之后挡住任务栏
		if( !isNew ) {
			this.MaximizedBounds = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
			this.BackColor = GUIset.FormColor;
			
			Point p0 = new Point(
				Screen.PrimaryScreen.WorkingArea.Width/2 - this.Width/2,
				Screen.PrimaryScreen.WorkingArea.Height/2 - this.Height/2 );
			this.Location = p0;
		}
		
		//this.BackColor = Color.SlateGray;//((SolidBrush)GUIset.BackBrush).Color;
		
		n_ControlCenter.ControlCenter.deleUseSerialPort = UseSerialPort;
		
		SimulateObj.deleOpenUart = OpenUart;
		SimulateObj.delePortValue = PortValue;
		SimulateObj.delePortRead = PortRead;
		
		n_UARTForm.UARTForm.deleGetSimStatus = GetSimStatus;
		n_UARTForm.UARTForm.deleSendData = SendData;
		n_RemoPad.RemoPad.deleSendData = SendData;
		
		n_ESP8266.ESP8266.d_SendByte = SendData;
		n_LAPI.LAPI.d_SendByte = SendData;
		
		BindExt = false;
		
		PortBuffer = new byte[MaxLength];
		CIndex = 0;
		RIndex = 0;
		
		n_Interface.AVM.D_ModuleWrite += ModuleWrite;
		n_Interface.AVM.D_ModuleRead += ModuleRead;
		
		n_ModuleLibPanel.MyModuleLibPanel.d_OpenLibMng = OpenLibMng;
		
		//G.ExampleBox.GPanel.OpenFile = OpenFile;
		
		this.Text = OS.USER;
		
		A.StartBox.AddMessage( "\n" );
		
		fm = new FormMover( this );
		
		AFileName = StartFileName;
		
		//添加默认程序文件
		if( AFileName == null ) {
			AFileName = n_StartFile.StartFile.CodeFile;
		}
		
		U.U.CPForm = new ClearChipForm();
		
		/*
		UserText = new RichTextBox();
		UserText.Dock = DockStyle.Fill;
		UserText.AcceptsTab = true;
		UserText.TextChanged += new System.EventHandler( UserTextChanged );
		
		//自动仿真时为空
		if( G.CodeViewBox != null ) {
			G.CodeViewBox.splitContainer1.Panel1.Controls.Add( UserText );
			G.CodeViewBox.D_SetUserText = SetUserText;
			G.CodeViewBox.D_GetUserText = GetUserText;
		}
		*/
		
		n_ImagePanel.ImagePanel.ExtOpenFile = ExtOpenFile;
		
		if( G.ExampleBox != null ) {
			G.ExampleBox.GPanel.OpenFile = OpenFile;
			G.ExampleBox.ShowOpenCheck();
		}
		
		n_CCode.CCode.SetUserCode = SetUserText;
		//GPanel = new PyPanel();
		//splitContainer2.Panel2.Controls.Add( GPanel );
		
		/*
		TexttabControl = new myTabControl();
		TexttabControl.Dock = DockStyle.Fill;
		//TexttabControl.SendToBack();
		//this.splitContainerMain.Panel2.Controls.Add( TexttabControl );
		G.CodeViewBox.Controls.Add( TexttabControl );
		
		//创建默认标签栏
		FileTabPage filePanel = new FileTabPage( TexttabControl );
		LaterFilePanel p = new LaterFilePanel();
		filePanel.Controls.Add( p );
		*/
		
		//splitContainer1.Panel2.Controls.Add( G.SimBox.panel3 );
	}
	
	static void ModuleWrite( int V1, int V2 )
	{
		int ModuleIndex = V1 / 65536;
		int Addr = V1 % 65536;
		
		//处理数据的仿真控件索引
		//int SimIndex = Addr / 4096;
		//Addr %= 4096;
		
		//判断是否为系统通信 (python)
		if( ModuleIndex == 0x1000 ) {
			
			n_Interface.AVM.SysTickTimer.Stop();
			
			n_PyVM.PyVM.ModuleWrite( Addr, V2 );
			
			n_Interface.AVM.SysTickTimer.Start();
			
			G.MyRefresh();
			G.CGPanel.MyRefresh();
			return;
		}
		//判断是否为系统通信 (python)  PYVM.Run 函数里用到了这个常量
		if( ModuleIndex == 0x1001 ) {
			
			//这里应该接收python里的延时函数, 并设置到py可视化界面上
			//...
			
			G.MyRefresh();
			G.CGPanel.MyRefresh();
			return;
		}
		
		n_MyObject.MyObject hm = (n_MyObject.MyObject)G.CGPanel.myModuleList.ModuleList[ModuleIndex];
		
		if( hm is n_HardModule.HardModule ) {
			n_HardModule.HardModule hh = (n_HardModule.HardModule)hm;
			if( hh.ImageName == n_GUIcoder.SPMoudleName.SYS_Sprite ) {
				n_Sprite.Sprite sp = (n_Sprite.Sprite )hh.TargetSObject;
				
				if( Addr == n_Sprite.Sprite.Addr_Sysmes ) {
					
					if( V2 == 0x00010000 ) {
						//创建角色
						hh.TargetSObject = G.SimBox.SPanel.Copy( (n_Sprite.Sprite)hh.CreateInitTargetSObject );
						hh.TargetSObject.Reset();
					}
					else if( V2 == 0x00010001 ) {
						//复制角色
						hh.TargetSObject = G.SimBox.SPanel.Copy( sp );
					}
					else if( V2 == 0x00010002 ) {
						//删除角色
						hh.TargetSObject = G.SimBox.SPanel.Delete( sp );
					}
					else if( V2 == 0x00010003 ) {
						//设置为第一个
						hh.TargetSObject = G.SimBox.SPanel.GetFirst( hh, 0 );
					}
					else if( V2 == 0x00010004 ) {
						//设置为最后一个
						hh.TargetSObject = G.SimBox.SPanel.GetEnd( hh, G.SimBox.SPanel.SLength - 1 );
					}
					else if( V2 == 0x00010005 ) {
						//切换到下一个
						hh.TargetSObject = G.SimBox.SPanel.GetFirst( hh, hh.TargetSObjectIndex + 1 );
					}
					else if( V2 == 0x00010006 ) {
						//切换到上一个
						hh.TargetSObject = G.SimBox.SPanel.GetEnd( hh, hh.TargetSObjectIndex - 1 );
					}
					else if( V2 == 0x00010007 ) {
						//事件触发扫描
						G.SimBox.SPanel.GetEvent( hh );
					}
					else {
						hh.TargetSObject = G.SimBox.SPanel.GetIndex( V2 );
					}
				}
				else if( Addr == n_Sprite.Sprite.Addr_Event ) {
					hm.DataList[Addr] = V2;
				}
				//else if( Addr == n_Sprite.Sprite.Addr_EventIndex ) {
				//	hm.DataList[Addr] = V2;
				//}
				else {
					if( sp == null ) {
						return;
					}
					if( sp.DataReceiveError( Addr, V2 ) ) {
						return;
					}
				}
			}
			else if( hh.ImageName == n_GUIcoder.SPMoudleName.SYS_View ) {
				G.SimBox.SPanel.DataReceive( Addr, V2 );
			}
			else {
				for( int i = 0; i < hh.SimList.Length; ++i ) {
					if( hh.SimList[i] != null ) {
						hh.SimList[i].ReceiveData( Addr, V2 );
					}
				}
			}
		}
		hm.DataList[Addr] = V2;
		hm.DataListChanged = true;
		
		G.MyRefresh();
		G.CGPanel.MyRefresh();
	}
	
	static int ModuleRead( int V1 )
	{
		int ModuleIndex = V1 / 65536;
		int Addr = V1 % 65536;
		
		//处理数据的仿真控件索引
		//int SimIndex = Addr / 4096;
		//Addr %= 4096;
		
		//判断是否为系统通信 (python)
		if( ModuleIndex == 0x1000 ) {
			
			return n_PyVM.PyVM.ModuleRead( Addr );
		}
		
		n_MyObject.MyObject hm = (n_MyObject.MyObject)G.CGPanel.myModuleList.ModuleList[ModuleIndex];
		
		n_HardModule.HardModule hh = (n_HardModule.HardModule)hm;
		if( hh.ImageName == n_GUIcoder.SPMoudleName.SYS_Sprite ) {
			
			if( Addr == n_Sprite.Sprite.Addr_Sysbool ) {
				return hh.TargetSObject != null? 1: 0;
			}
			else if( Addr == n_Sprite.Sprite.Addr_Systid ) {
				if( hh.TargetSObject == null ) {
					//n_SimPanel.SimPanel.DebugMes += "SysidNull ";
					return -1;
				}
				else {
					return hh.TargetSObject.Index;
				}
			}
			else if( Addr == n_Sprite.Sprite.Addr_Event ) {
				return hm.DataList[Addr];
			}
			else if( Addr == n_Sprite.Sprite.Addr_EventIndex ) {
				return hm.DataList[Addr];
			}
			else {
				if( hh.TargetSObject == null ) {
					n_SimPanel.SimPanel.DebugMes += "GError\n";
					return -1;
				}
				else {
					n_Sprite.Sprite sp = (n_Sprite.Sprite )hh.TargetSObject;
					return sp.DataRead( Addr );
				}
			}
		}
		else if( hh.ImageName == n_GUIcoder.SPMoudleName.SYS_View ) {
			return G.SimBox.SPanel.DataRead( Addr );
		}
		else {
			for( int i = 0; i < hh.SimList.Length; ++i ) {
				if( hh.SimList[i] != null ) {
					hh.SimList[i].GetData( Addr );
				}
			}
		}
		return hm.DataList[Addr];
	}
	
	//override
	protected override void WndProc(ref Message msg)
	{
		base.WndProc(ref msg);
		switch (msg.Msg)
		{
			case WM_HOTKEY: //窗口消息：热键
				int tmpWParam = msg.WParam.ToInt32();
				if( tmpWParam == HotKeyID ) {
					if( G.ScreenBox == null ) {
						G.ScreenBox = new n_ScreenForm.ScreenForm();
					}
					if( !G.ScreenBox.Visible ) {
						G.ScreenBox.Run();
					}
				}
				break;
			case WM_CREATE: //窗口消息：创建
				
				Keys k = Keys.None;
				switch( n_MainSystemData.SystemData.ScreenKey ) {
					case 0:		k = Keys.F1; break;
					case 1:		k = Keys.F2; break;
					case 2:		k = Keys.F3; break;
					case 3:		k = Keys.F4; break;
					case 4:		k = Keys.F5; break;
					case 5:		k = Keys.F6; break;
					case 6:		k = Keys.F7; break;
					case 7:		k = Keys.F8; break;
					case 8:		k = Keys.F9; break;
					case 9:		k = Keys.F10; break;
					case 10:	k = Keys.F11; break;
					case 11:	k = Keys.F12; break;
					default:	break;
				}
				if( k != Keys.None ) {
					SystemHotKey.RegHotKey( this.Handle, HotKeyID, SystemHotKey.KeyModifiers.None, k );
				}
				
				break;
			case WM_DESTROY: //窗口消息：销毁
				SystemHotKey.UnRegHotKey(this.Handle, HotKeyID); //销毁热键
				break;
			default:
				break;
		}
	}
	
	//override
	protected void WndProcTemp(ref Message m)
	{
		if(m.Msg == (int)WinMsg.WM_NCPAINT) {
			return;
		}
		else if(m.Msg == (int)WinMsg.WM_NCCALCSIZE) {
			return;
		}
		else if(m.Msg == (int)WinMsg.WM_NCACTIVATE) {
			if (m.WParam == (IntPtr)0) {
				m.Result = (IntPtr)1;
			}
		}
		else if(m.Msg == (int)WinMsg.WM_NCHITTEST) {
			bool CanResize = true;
			if(CanResize == true) {
				Point point = new Point(m.LParam.ToInt32());
				int x = point.X;
				int y = point.Y;
				if (x <= this.Left + MovePadding && y <= this.Top + MovePadding) {
					m.Result = (IntPtr)HitTest.HTTOPLEFT;
				}
				else if(x >= this.Right - MovePadding && y <= this.Top + MovePadding) {
					m.Result = (IntPtr)HitTest.HTTOPRIGHT;
				}
				else if(x >= this.Right - MovePadding && y >= this.Bottom - MovePadding) {
					m.Result = (IntPtr)HitTest.HTBOTTOMRIGHT;
				}
				else if(x <= this.Left + MovePadding && y >= this.Bottom - MovePadding) {
					m.Result = (IntPtr)HitTest.HTBOTTOMLEFT;
				}
				else if(x <= this.Left + MovePadding) {
					m.Result = (IntPtr)HitTest.HTLEFT;
				}
				else if(y <= this.Top + MovePadding) {
					m.Result = (IntPtr)HitTest.HTTOP;
				}
				else if(x >= this.Right - MovePadding) {
					m.Result = (IntPtr)HitTest.HTRIGHT;
				}
				else if(y >= this.Bottom - MovePadding) {
					m.Result = (IntPtr)HitTest.HTBOTTOM;
				}
				else {
					m.Result = (IntPtr)HitTest.HTCAPTION;
				}
			}
			else {
				//m.Result = (IntPtr)Win32.HTCAPTION;
				Win32API.ReleaseCapture();
				int SC_MOVE = 0xF012;
				Win32API.SendMessage(this.Handle, (int)WinMsg.WM_SYSCOMMAND, (int)(SC_MOVE + HitTest.HTCAPTION), (IntPtr)0);

			}
		}
		else {
			base.WndProc(ref m);
		}
	}
	
	void ExtOpenFile( string filename )
	{
		OpenFile( false, filename );
	}
	
	//----------------------------------------------------------------
	
	void OpenPython()
	{
		T.T.m.Run();
	}
	
	void Setting()
	{
		if( U.U.SysBox == null ) {
			U.U.SysBox = new n_SysForm.SysForm();
		}
		U.U.SysBox.Run();
	}
	
	void OpenFile()
	{
		if( n_MainSystemData.SystemData.ExtMes != "" ) {
			MessageBox.Show( "比赛版本不允许打开已有的程序文件" );
			return;
		}
		
		//打开文件对话框
		OpenFileDialog OpenFileDlg = new OpenFileDialog();
		OpenFileDlg.Filter = n_CCode.CCode.Filter;
		OpenFileDlg.Title = "请选择文件";
		
		if( !G.ccode.isStartFile ) {
			OpenFileDlg.InitialDirectory = G.ccode.FilePath;
		}
		
		DialogResult dlgResult = OpenFileDlg.ShowDialog();
		if(dlgResult == DialogResult.OK) {
			OpenFile( false, OpenFileDlg.FileName );
		}
	}
	
	void NewFile()
	{
		//保存文件对话框
		SaveFileDialog SaveFileDlg = new SaveFileDialog();
		SaveFileDlg.Filter = n_CCode.CCode.Filter;
		SaveFileDlg.Title = "保存文件";
		
		SaveFileDlg.FileName = n_CCode.CCode.GetLinkboyFileName();
		DialogResult dlgResult = SaveFileDlg.ShowDialog();
		if(dlgResult == DialogResult.OK) {
			string FilePath = SaveFileDlg.FileName;
			if( !FilePath.ToLower().EndsWith( "." + OS.LinkboyFile ) ) {
				FilePath += "." + OS.LinkboyFile;
			}
			if( System.IO.File.Exists( FilePath ) ) {
				MessageBox.Show( "当前位置已存在相同名字的文件, 不允许新建同名的文件!" );
				return;
			}
			
			System.IO.File.Copy(  n_StartFile.StartFile.CodeFile, FilePath );
			
			//创建文档
			OpenFile( false, FilePath );
		}
	}
	
	void SaveAsFile()
	{
		//保存文件对话框
		SaveFileDialog SaveFileDlg = new SaveFileDialog();
		SaveFileDlg.Filter = n_CCode.CCode.Filter;
		SaveFileDlg.Title = "文件另存为...";
		
		SaveFileDlg.FileName = n_CCode.CCode.GetLinkboyFileName();
		DialogResult dlgResult = SaveFileDlg.ShowDialog();
		if(dlgResult == DialogResult.OK) {
			string FilePath = SaveFileDlg.FileName;
			if( !FilePath.ToLower().EndsWith( "." + OS.LinkboyFile ) ) {
				FilePath += "." + OS.LinkboyFile;
			}
			
			G.ccode.GUItext = myGFilePanel.GPanel.VarToText();
			G.ccode.SetCode( G.ccode.UserText, G.ccode.GUItext );
			
			VIO.SaveTextFile( FilePath, G.ccode.GetCode() );
			
			//创建文档
			OpenFile( true, FilePath );
			
			MessageBox.Show( "注意: 当前打开的为另存后的新文件:\n" + FilePath, "文件路径提示" );
		}
	}
	
	void ToolBox()
	{
		if( U.U.ToolBox == null ) {
			U.U.ToolBox = new n_GToolForm.ToolForm();
		}
		U.U.ToolBox.Run();
	}
	
	void PyBox()
	{
		if( SplitValue == 0 ) {
			SplitValue = Width * 2 / 3;
		}
		if( Width - SplitValue < 5 ) {
			SplitValue = Width * 2 / 3;
			//MessageBox.Show( "PyBox距离异常, 已修复." );
		}
		buttonFull.Visible = true;
		buttonStep.Visible = true;
		buttonPyLang.Visible = true;
		buttonCopy.Visible = false;
		
		CPanel.SetPyMode( true );
		splitContainer1.SplitterDistance = SplitValue;
		splitContainer1.SplitterWidth = 15;
		
		G.ShowPythonBox = true;
	}
	
	void UserCodeBox()
	{
		if( SplitValue == 0 ) {
			SplitValue = Width * 2 / 3;
		}
		
		buttonFull.Visible = false;
		buttonStep.Visible = false;
		buttonPyLang.Visible = false;
		buttonCopy.Visible = true;
		
		
		//由于着色太费时间, 不再处理
		CPanel.Sys_ctext.EnableColor = false;
		
		
		CPanel.Sys_ctext.Text = n_GUIcoder.GUIcoder.SysCode;
		
		CPanel.Sys_ctext.DrawAllArea();
		
		CPanel.SetPyMode( false );
		splitContainer1.SplitterDistance = SplitValue;
		splitContainer1.SplitterWidth = 15;
		
		G.ShowPythonBox = true;
	}
	
	//----------------------------------------------------------------
	
	void OpenUart()
	{
		if( U.U.UARTBox == null ) {
			U.U.UARTBox = new n_UARTForm.UARTForm();
		}
		U.U.UARTBox.Run();
	}
	
	void PortValue( int d )
	{
		if( U.U.UARTBox != null ) {
			U.U.UARTBox.ReceiveByte( (byte)d );
		}
		n_LAPI.LAPI.AddByte( (byte)d );
		
		//8266应该增加一个开启关闭函数, 根据界面是否有8266模块来自动设置
		n_ESP8266.ESP8266.AddByte( (byte)d );
	}
	
	bool GetSimStatus()
	{
		return G.SimulateMode;
	}
	
	void SendData( byte b )
	{
		PortBuffer[CIndex] = b;
		++CIndex;
		CIndex %= MaxLength;
	}
	
	int PortRead()
	{
		if( RIndex == CIndex ) {
			return -1;
		}
		byte b = PortBuffer[RIndex];
		++RIndex;
		RIndex %= MaxLength;
		return b;
	}
	
	
	void DeleFTPButton()
	{
		if( U.U.NewVersionBox == null ) {
			U.U.NewVersionBox = new NewVersionForm();
		}
		U.U.NewVersionBox.Visible = true;
	}
	
	void UseSerialPort()
	{
		try {
		if( U.U.UARTBox == null ) {
			U.U.UARTBox = new n_UARTForm.UARTForm();
		}
		if( U.U.UARTBox.isOpen ) {
			U.U.UARTBox.Button打开串口Click( null, null );
		}
		
		if( U.U.CWaveBox == null ) {
			U.U.CWaveBox = new n_CWaveForm.CWaveForm();
		}
		if( U.U.CWaveBox.isOpen ) {
			U.U.CWaveBox.Button打开串口Click( null, null );
		}
		
		if( U.U.CMusicBox == null ) {
			U.U.CMusicBox = new n_CMusicForm.CMusicForm();
		}
		if( U.U.CMusicBox.isOpen ) {
			U.U.CMusicBox.Button打开串口Click( null, null );
		}
		}
		catch {
			MessageBox.Show( "初始化串口控件类时遇到了一点问题, 暂不影响您使用, 但建议您向我们反馈此问题, 以便后续改进" );
		}
	}
	
	//打开模块库管理器
	void OpenLibMng()
	{
		if( n_Service.Program.mf == null ) {
			n_Service.MainForm.Mode = 2;
			n_Service.Program.Init();
			n_Service.Program.mf.SetAccel();
		}
		n_Service.Program.mf.Run();
	}
	
	//打开新文件
	void d_OpenFile( bool IgnoreSave, string FileName )
	{
		OpenFile( IgnoreSave, FileName );
		if( A.StartFileName != null ) {
			G.ccode.isStartFile = false;
			G.ccode.PathAndName = A.StartFileName;
			G.ccode.GetFileNameAndPath();
		}
	}
	
	//打开新文件
	public void OpenFile( bool IgnoreSave, string FileName )
	{
		//判断上一个是否需要关闭
		if( myGFilePanel != null ) {
			if( !IgnoreSave && !myGFilePanel.TryClose() ) {
				return;
			}
			this.Controls.Remove( myGFilePanel );
		}
		this.splitContainer1.Panel1.Controls.Clear();
		System.Windows.Forms.Application.DoEvents();
		
		//添加到近期文档列表
		if( !G.AutoRunMode && !n_StartFile.StartFile.isStartFile( FileName ) ) {
			LaterFilesManager.AddFile( FileName );
		}
		//创建一个新的图形控件
		myGFilePanel = new GFilePanel( FileName, this.Width, this.Height );
		G.CGPanel = myGFilePanel.GPanel;
		
		myGFilePanel.GPanel.GHead.Python = OpenPython;
		myGFilePanel.GPanel.GHead.Setting = Setting;
		myGFilePanel.GPanel.GHead.DeleNewFile = NewFile;
		myGFilePanel.GPanel.GHead.DeleOpenFile = OpenFile;
		myGFilePanel.GPanel.GHead.DeleSaveAsFile = SaveAsFile;
		myGFilePanel.GPanel.GHead.DeleToolBox = ToolBox;
		myGFilePanel.GPanel.GHead.DelePy = PyBox;
		myGFilePanel.GPanel.GHead.DeleUserCode = UserCodeBox;
		myGFilePanel.GPanel.STip.DeleFTPButton = DeleFTPButton;
		
		myGFilePanel.GPanel.GHead.TargetForm = this;
		
		myGFilePanel.GPanel.STip.OpenFile = d_OpenFile;
		
		
		if( !n_StartFile.StartFile.isStartFile( FileName ) ) {
			
			//这里说明是双击文件打开的或者点击了打开文件按钮
			if( n_ModuleLibPanel.MyModuleLibPanel.LabType == n_GUIcoder.labType.Default ) {
				n_ModuleLibPanel.MyModuleLibPanel.LabType = n_GUIcoder.labType.Code;
			}
			//确保是双击打开文件的步骤
			if( n_ModuleLibPanel.MyModuleLibPanel.FloatButton ) {
				n_ModuleLibPanel.MyModuleLibPanel.Init( n_ModuleLibPanel.MyModuleLibPanel.LabType );
				G.CGPanel.GHead.MoButton_MouseDownEvent();
			}
		}
		
		
		//this.Controls.Clear();
		//this.Controls.Add( myGFilePanel );
		this.splitContainer1.Panel1.Controls.Add( myGFilePanel );
		
		//由于是Fill 所以需要放到添加到controls之后
		G.CGPanel.GHead.SizeChanged( null, null );
		
		G.CGPanel.Invalidate();
		
		//全局文件夹遍历更新程序时才使用
		//myGFilePanel.ccode.Save();
		
		//n_Debug.Debug.Message += "A: " + (G.ccode != null? G.ccode.isChanged.ToString() : "NULL") + "\n";
		
		if( G.SimulateMode ) {
			n_ControlCenter.ControlCenter.StopSim();
		}
		if( !G.ccode.ExistPython() ) {
			//ButtonHideClick( null, null );
		}
		else {
			PyBox();
		}
	}
	
	//窗体关闭事件
	void GFormFormClosing(object sender, FormClosingEventArgs e)
	{
		if( G.SimulateMode ) {
			
			n_ControlCenter.ControlCenter.StopSim();
			
			//这里主要用于 游戏动画仿真结束没有调用 Reload 函数
			//e.Cancel = true;
			//Debug.Meesage = ( "请先结束仿真再关闭软件" );
			//return;
		}
		
		if( myGFilePanel != null ) {
			if( !myGFilePanel.TryClose() ) {
				e.Cancel = true;
				return;
			}
		}
	}
	
	//窗体尺寸改变事件
	void GFormResize(object sender, EventArgs e)
	{
		n_ImagePanel.ImagePanel.FormWidth = Width;
		n_ImagePanel.ImagePanel.FormHeight = Height;
		
		if( myGFilePanel != null ) {
			myGFilePanel.GPanel.GHead.SizeChanged( null, null );
			myGFilePanel.GPanel.Invalidate();
		}
	}
	
	//窗体加载
	public void GFormLoad(object sender, EventArgs e)
	{
		G.ShowPythonBox = true;
		ButtonHideClick( null,null);
		/*
		//判断是否双击程序本身打开
		if( AFileName != null ) {
			
			if( n_MainSystemData.SystemData.ExtMes != "" ) {
				if( AFileName != n_StartFile.StartFile.SFile ) {
					AFileName = n_StartFile.StartFile.SFile;
					MessageBox.Show( "比赛版本不允许打开已有的程序文件" );
				}
			}
			OpenFile( true, AFileName );
		}
		*/
		//创建发现新版本窗体
		//U.U.NewVersionBox = new n_NewVersionForm.NewVersionForm();
		
		timer1.Enabled = true;
		
		GFormResize( null, null );
		
		SplitValue = 0;
		
		A.StartBox.Visible = false;
		A.StartBox.Dispose();
	}
	
	void Timer1Tick(object sender, EventArgs e)
	{
		//判断是否双击程序本身打开
		if( AFileName != null ) {
			timer1.Enabled = false;
			if( n_MainSystemData.SystemData.ExtMes != "" ) {
				//if( n_StartFile.StartFile.isStartFile( AFileName ) ) {
				//	AFileName = n_StartFile.StartFile.CodeFile;
				//	MessageBox.Show( "比赛版本不允许打开已有的程序文件" );
				//}
			}
			OpenFile( true, AFileName );
			AFileName = null;
			timer1.Enabled = true;
		}
		//更新标题栏文件修改标志
		if( !n_ModuleLibPanel.MyModuleLibPanel.FloatButton && this.Text != G.CGPanel.GHead.NewHeadLabel.SoftText ) {
			this.Text = G.CGPanel.GHead.NewHeadLabel.SoftText;
		}
		//判断是否需要显示新版本功能窗体
		if( U.U.VersionBox == null && n_MainSystemData.SystemData.ShowNewVersion ) {
			U.U.VersionBox = new n_VersionForm.VersionForm();
			U.U.VersionBox.Show();
		}
		if( !BindExt ) {
			BindExt = true;
			ExtNameBind.FileExternNameReg_Linkboy();
			if( n_OS.OS.USER == n_OS.OS.USER_linkboy ) {
				//ExtNameBind.FileExternNameReg_Remo();
				ExtNameBind.FileExternNameReg_Iny();
			}
		}
	}
	
	void TabControl1Click(object sender, EventArgs e)
	{
		ShowMes();
	}
	
	//=======================================================================================
	
	//开始编译处理
	void Start( bool isShowForm )
	{
		n_OutputBox.OutputBox.Clear();
		ErrorListBox.Clear();
		if( isShowForm ) {
			//ShowMes();
		}
		CPanel.SimcurrentLine = -1;
		
		if( G.ccode.b_ExistPython ) {
			//mmTimer1.Start();
		}
	}
	
	//显示错误信息
	void ShowError( bool defaultL )
	{
		ShowMes();
		if( defaultL ) {
			ErrorListBox.ShowError( n_ET.ET.Show().Split( '\n' ) );
		}
		else {
			ErrorListBox.ShowError( n_PyET.ET.Show().Split( '\n' ) );
		}
		if( !G.ShowPythonBox && G.ccode.ExistPython() ) {
			PyBox();
		}
	}
	
	//隐藏错误信息
	void HiddError()
	{
		HideMes();
	}
	
	//弹出信息栏
	void ShowMes()
	{
		int c = splitContainer3.Height - 230;
		if( c < 0 ) {
			c = 0;
		}
		splitContainer3.SplitterDistance = c;
	}
	
	//隐藏信息栏
	public void HideMes()
	{
		try {
			splitContainer3.SplitterDistance = splitContainer3.Height - 2;
		}
		catch {
			MessageBox.Show( "ERR:HideMes()" );
			//...
		}
	}
	
	//=======================================================================================
	
	//PyPanel GPanel;
	
	//设置当前将要执行的代码行
	void SetCLine( int line )
	{
		//Text = line.ToString();
		
		/*
		int sindex = richTextBox1.GetFirstCharIndexFromLine( line );
		richTextBox1.SelectionStart = sindex;
		richTextBox1.SelectionLength = richTextBox1.Lines[line].Length;
		
		richTextBox1.Focus();
		*/
		
		CPanel.SimcurrentLine = line;
		CPanel.LineLabel.Refresh();
	}
	
	//设置用户代码
	public void SetUserText( string s )
	{
		CPanel.ctext.Text = s;
	}
	
	//获取用户代码
	public string GetUserText()
	{
		return "";
		
		//return CPanel.ctext.Text;
	}
	
	void RunStep()
	{
		PyVM.PCStep = false;
		PyVM._wh.Set();
		
		/*
		PyVM._wh11.WaitOne();
		
		PyVM.isOk = false;
		n_PyVar.PyVar.MyRefresh();
		GPanel.MyRefresh();
		SetCLine( n_PyVar.PyVar.CLine - 1 );
		*/
		//Application.DoEvents();
	}
	
	void MmTimer1Tick(object sender, EventArgs e)
	{
		if( CPanel.SimcurrentLine == -1 ) {
			CPanel.SimcurrentLine = 0;
			CPanel.LineLabel.Refresh();
			return;
		}
		//GPanel.MyRefresh();
		
		if( StepOpen ) {
			if( StepTick == 0 ) {
				RunStep();
			}
			++StepTick;
			if( StepTick >= MaxStepTick ) {
				StepTick = 0;
			}
		}
		
		if( PyVM.isOk || PyVM.isFullSpeed ) {
			PyVM.isOk = false;
			n_PyVar.PyVar.MyRefresh();
			//GPanel.MyRefresh();
			SetCLine( n_PyVar.PyVar.CLine );
			
			//Refresh();
			//n_Debug.Debug.Message += "A";
		}
		if( (!PyVM.isFullSpeed && !StepOpen) || !G.SimulateMode ) {
			mmTimer1.Stop();
		}
	}
	
	void ButtonResultClick(object sender, EventArgs e)
	{
		//获取编译字节码
		G.ccode.UserText = GetUserText();
		string s = n_GUIcoder.GUIcoder.GetUserProgram();
		
		//获取编译结果
		StringBuilder result = new StringBuilder( "" );
		
		//result.Append( "****************元件列表:****************\n" );
		//try { result.Append( n_PyUnitList.UnitList.Show() ); } catch {}
		
		//result.Append( "****************虚拟类型列表:****************\n" );
		//try { result.Append( n_PyVdataList.VdataList.Show() ); } catch {}
		
		//result.Append( "***************结构体列表:***************\n" );
		//try { result.Append( n_PyStructList.StructList.Show() ); } catch {}
		
		result.Append( "****************类列表:****************\n" );
		try { result.Append( n_PyUnitList.UnitList.Show() ); } catch {}
		
		result.Append( "****************函数列表:****************\n" );
		try { result.Append( n_PyFunctionList.FunctionList.Show() ); } catch {}
		
		result.Append( "****************变量列表:****************\n" );
		try { result.Append( n_PyVarList.VarList.Show() ); } catch {}
		
		result.Append( "****************标号列表:****************\n" );
		try { result.Append( n_PyLabelList.LabelList.Show() ); } catch {}
		
		result.Append( "****************词法列表:****************\n" );
		try { result.Append( n_PyWordList.WordList.Show() ); } catch {}
		
		result.Append( "****************语法列表:****************\n" );
		try { result.Append( n_PyParseNet.ParseNet.Show() ); } catch {}
		
		result.Append( "****************源程序:****************\n" );
		try { result.Append( n_PyAccidence.Accidence.Source ); } catch {}
		
		G.CodeBox.SetResult( result.ToString() );
		
		G.CodeBox.Run();
	}
	
	void ButtonPCStepClick(object sender, EventArgs e)
	{
		mmTimer1.Stop();
		
		PyVM.PCStep = true;
		PyVM._wh.Set();
		
		int tick = 0;
		while( PyVM.isOk && tick < 10 ) {
			System.Threading.Thread.Sleep( 50 );
			tick++;
		}
		n_PyVar.PyVar.MyRefresh();
		//GPanel.MyRefresh();
		G.CodeBox.SetLine( n_PyVar.PyVar.PC );
		G.CodeBox.Refresh();
		G.CodeBox.Activate();
	}
	
	void ButtonSwitchClick(object sender, EventArgs e)
	{
		n_PyVar.PyVar.DrawType++;
		if( n_PyVar.PyVar.DrawType == 2 ) {
			n_PyVar.PyVar.DrawType = 0;
		}
		n_PyVar.PyVar.MyRefresh();
		//GPanel.MyRefresh();
	}
	
	//=============================================================
	//单步执行
	
	bool StepOpen;
	int StepTick;
	int MaxStepTick;
	
	int SuperTick = 0;
	
	Image stepi;
	
	void ButtonStepMouseDown(object sender, MouseEventArgs e)
	{
		//判断是否显示调试控件
		if( e.Button == MouseButtons.Right ) {
			SuperTick++;
			if( SuperTick == 10 ) {
				panel3.Visible = true;
			}
			return;
		}
		buttonFull.BackColor = Color.Transparent;
		buttonStep.BackColor = Color.Khaki;
		
		//启动单步调试器
		PyVM.isFullSpeed = false;
		G.CGPanel.SkipRefresh = false;
		StepOpen = true;
		StepTick = 0;
		MaxStepTick = 100 * e.X / buttonStep.Width;
		mmTimer1.Start();
	}
	
	void ButtonStepMouseUp(object sender, MouseEventArgs e)
	{
		G.CGPanel.SkipRefresh = true;
		StepOpen = false;
		
		CPanel.ctext.Focus();
	}
	
	void ButtonStepMouseMove(object sender, MouseEventArgs e)
	{
		int mtick = 100 * e.X / buttonStep.Width;
		
		buttonStep.Text = "每" + (mtick * 0.01).ToString( "f1" ) + "秒执行一步";
		
		if( e.Button == MouseButtons.Left ) {
			MaxStepTick = mtick;
			buttonStep.Refresh();
		}
	}
	
	void ButtonStepMouseEnter(object sender, EventArgs e)
	{
		stepi = buttonStep.BackgroundImage;
		//buttonStep.BackgroundImage = null;
		buttonStep.Text = "单步执行";
	}
	
	void ButtonStepMouseLeave(object sender, EventArgs e)
	{
		buttonStep.BackgroundImage = stepi;
		buttonStep.Text = "";
	}
	
	//=============================================================
	
	void SplitContainer1SplitterMoved(object sender, SplitterEventArgs e)
	{
		//SplitValue = splitContainer1.SplitterDistance;
	}
	
	//隐藏py和代码窗口
	void ButtonHideClick(object sender, EventArgs e)
	{
		if( G.ShowPythonBox ) {
			SplitValue = splitContainer1.SplitterDistance;
			splitContainer1.SplitterWidth = 1;
			splitContainer1.SplitterDistance = splitContainer1.Width - 2;
			
			G.ShowPythonBox = false;
		}
		
	}
	
	//=============================================================
	Image fulli;
	
	void ButtonFullClick(object sender, EventArgs e)
	{
		buttonFull.BackColor = Color.Khaki;
		buttonStep.BackColor = Color.Transparent;
		
		PyVM.isFullSpeed = true;
		PyVM._wh.Set();
		
		CPanel.ctext.Focus();
	}
	
	void ButtonFullMouseEnter(object sender, EventArgs e)
	{
		fulli = buttonFull.BackgroundImage;
		//buttonFull.BackgroundImage = null;
		buttonFull.Text = "高速";
	}
	
	void ButtonFullMouseLeave(object sender, EventArgs e)
	{
		buttonFull.BackgroundImage = fulli;
		buttonFull.Text = "";
	}
	
	//=============================================================
	
	void ButtonPyLangClick(object sender, EventArgs e)
	{
		if( U.U.PyLangBox == null ) {
			U.U.PyLangBox = new n_PyLangForm.PyLangForm();
		}
		U.U.PyLangBox.Run();
	}
	
	void ButtonCopyClick(object sender, EventArgs e)
	{
		CPanel.Sys_ctext.SelectAll();
		CPanel.Sys_ctext.Copy();
	}
}
}

